﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using Servidor.Xml;
using Servidor.Dominio;
using Servidor.Logica;

namespace Servidor
{
    public class servidor
    {
        TcpListener tcpListener;

        public void encender()
        {
            tcpListener = new TcpListener(7892);
            Console.WriteLine("Servidor");
            Console.WriteLine("ESPERANDO UN CLIENTE");
        }

        public void escuchar()
        {

            while (true)
            {
                tcpListener.Start();
                Socket socketParaCliente = tcpListener.AcceptSocket();
                if (socketParaCliente.Connected)
                {
                    Console.WriteLine("Se ha conectado un cliente");

                    NetworkStream networkStream = new NetworkStream(socketParaCliente);

                    StreamReader streamReader = new StreamReader(networkStream);

                    StreamWriter streamWriter = new StreamWriter(networkStream);


                    try
                    {
                        String peticion = streamReader.ReadLine(); 
                        String operacion = peticion.Substring(0,1);
                        peticion = peticion.Substring(1, peticion.Length - 1); 
                        
                        if (operacion == "L")
                        {
                            if (metodosServidor.validarTarjeta(peticion))
                            {
                                streamWriter.WriteLine("O");
                            }
                            else
                            {
                                streamWriter.WriteLine("N");
                            }
                        }

                        else if (operacion == "M")
                        {
                            metodosServidor.cambiarClave(peticion);
                        }

                        else if (operacion == "H")
                        {
                            String cuentas = metodosServidor.informacionCuentas(peticion);
                            streamWriter.WriteLine(cuentas);
                        }
                        
                        streamWriter.Flush();

                        Console.WriteLine("Cliente dice : " + peticion);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }

                    finally
                    {
                        streamReader.Close();
                        streamWriter.Close();
                        networkStream.Close();
                        socketParaCliente.Close();
                    }

                }

            }

        }

    }
}
